<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 使用左侧插槽 -->
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <!-- 使用右侧插槽 -->
        <template #right>
          <el-button type="warning" size="small" @click="showExcelDialog = true">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 卡片部分 -->
      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column type="index" label="序号" />
          <el-table-column label="头像" align="center">
            <template #default="{ row }">
              <img v-if="row.staffPhoto" class="avatar" :src="row.staffPhoto" />
              <img v-else class="avatar" src="@/assets/common/bigUserHeader.png" />
            </template>
          </el-table-column>

          <el-table-column align="center" prop="username" label="姓名" />
          <el-table-column align="center" prop="mobile" label="手机号" />
          <el-table-column align="center" prop="workNumber" label="工号" />
          <el-table-column align="center" label="聘用形式">
            <template v-slot="{ row }">
              <!-- {{ row.formOfEmployment === 1 ? '正式' : '非正式' }} -->
              <!-- 或者用枚举的方法 -->
              {{ formOfEmployment(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" />
          <el-table-column align="center" prop="timeOfEntry" sortable label="入职时间" />
          <el-table-column label="操作" width="200px" align="center">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button v-allow="'assign_role'" type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination background :current-page="q.page" :page-size="q.pagesize" layout="total,  prev, pager, next, jumper" :total="total" @current-change="hCurrentChange" />
      </el-row>
      <!-- 弹层dialog -->
      <el-dialog title="添加" :visible.sync="showDialog" width="45%" :close-on-press-escape="false" :close-on-click-modal="false">
        <emp-dialog v-if="showDialog" ref="fromDialog" @successChange="hSuccess" />
      </el-dialog>
      <!-- 分配权限的dialog -->
      <el-dialog title="添加" :visible.sync="showDialogRole" width="45%" :close-on-press-escape="false" :close-on-click-modal="false">
        <assign-role v-if="showDialogRole" :id="currentId" @cancel="hCancel" />
      </el-dialog>
    </div>
    <!-- 导入excel -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @success="loadGetEmployeesList" />
  </div>
</template>

<script>
import { delEmployee, getEmployees } from '@/api/employees'
import EmployeeConst from '@/constant/employees.js'
import empDialog from './empDialog.vue'
import ImportExcel from './components/import-excel.vue'
// import fileSaver from 'file-saver'
import { transExcelHeader } from '@/utils'
import AssignRole from './assignRole.vue'

// 把数组转成  obj:{'1':'正式', '2':'非正式'}，然后用obj["1"]就可以获取到,不用放到formOfEmployment函数里面，不用每次都循环
const hireType = {}
EmployeeConst.hireType.map(ele => (hireType[ele.id] = ele.value))
// console.log(hireType)
export default {
  name: 'EmployeesIndex',
  components: { empDialog, ImportExcel, AssignRole },

  data() {
    return {
      q: {
        page: 1,
        pagesize: 4
      },
      list: [],
      total: 0,
      currentId: '',
      showDialog: false,
      showExcelDialog: false,
      showDialogRole: false // 分配权限的dialog
    }
  },

  created() {
    this.loadGetEmployeesList()
    // console.log(this.$MyUI)
  },

  methods: {
    // 获取员工列表
    async loadGetEmployeesList() {
      try {
        const { data } = await getEmployees(this.q)
        // console.log(data)
        this.list = data.rows
        this.total = data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 点击分页，跳转，刷新数据
    hCurrentChange(val) {
      // console.log(val)
      this.q.page = val
      this.loadGetEmployeesList()
    },
    // 用枚举渲染聘用形式
    formOfEmployment(code) {
      return hireType[code]
    },
    // 删除员工
    async del(row) {
      // console.log(row)
      try {
        // 提示用户是否要删除
        await this.$confirm('您确认要删除吗?', '提示', {
          type: 'warning'
        })
        // console.log(11)
        const res = await delEmployee(row.id)
        // // console.log(res)
        // // 提示用户删除成功
        this.$message.success(res.message)
        // 要先判断是不是当前的最后一条
        if (this.list.length === 1 && this.q.page > 1) this.q.page--
        // 从新渲染页面
        this.loadGetEmployeesList()
      } catch (error) {
        if (error === 'cancel') return
        this.$message.error(error.message)
      }
    },

    // 子组件新增员工成功之后，父组件关闭dialog
    hSuccess() {
      this.showDialog = false
      // 处理添加成功之后的页码值跳转的问题
      if (this.total % this.q.pagesize === 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.pagesize)
      // 从新渲染数据
      this.loadGetEmployeesList()
    },
    //   "file-saver":{
    //  " version": "2.0.5",
    //  " resolved":"https://registry.npmmirror.com/file-saver/-/file-saver-2.0.5.tgz#d61cfe2ce059f414d899e9dd6d4107ee25670c38",
    //  " integrity": "sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA==",
    //  "dev": true
    // },

    // 导出excel
    // async exportExcel() {
    //   const res = await exportExcel()
    //   console.log(res)
    //   // 参数1: blob 对象
    //   // 参数2: 文件名
    //   fileSaver.saveAs(res, '员工信息表.xlsx')
    // },
    // 导出excel要处理下数据
    async exportExcel() {
      // 发请求拿到所有的导出数据
      const { data } = await getEmployees({ page: 1, pagesize: this.total })
      // console.log(data)
      this.hExpoertExcel(data)
    },
    // 封装一个导出的函数
    async hExpoertExcel(list) {
      // 对数据做处理,如果没有拿到数据，没有第一个数据，就不往下走了
      // 把表头改为中文的
      const hdata = transExcelHeader(list)
      if (!list.rows[0]) return
      // 如果有数据的话就取出header
      const header = Object.keys(hdata[0])
      const data = hdata.map(ele => Object.values(ele))

      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        // header: ['姓名', '性别'], // 表头 必填
        // data: [ ['刘备', '男'],['关羽', '男'] ],  具体数据，是个二维数组 必填
        header, // 表头 必填
        data,
        filename: '导出员工', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    },
    // 取消分配权限的dialog
    hCancel() {
      this.showDialogRole = false
    },
    // 点击分配角色
    hAssign(id) {
      this.showDialogRole = true
      this.currentId = id
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar {
  height: 45px;
  width: 45px;
  border-radius: 50%;
}
</style>
